package com.yokit.resource_management.framework.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yokit.resource_management.dto.ResersvationRoomCar;
import com.yokit.resource_management.dto.ResponseDto;
import com.yokit.resource_management.entity.Reservation;
import com.yokit.resource_management.framework.service.ReserveService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fengzeng
 * @create 2021/6/25 3:02
 */
@RestController
public class ReserveController {
  static final String TYPE_CAR = "car";
  static final String TYPE_ROOM = "room";
  @Resource
  private ReserveService reserveService;

  /**
   * 分页查询预约表的所有信息
   *
   * @param pageNum
   * @param pageSize
   * @return
   */
  @RequestMapping(value = "/reserveList/{status}", method = RequestMethod.GET)
  public Map getReservationList(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @PathVariable String status) {
    List<ResersvationRoomCar> cars = reserveService.SelectAllCar();
    List<ResersvationRoomCar> rooms = reserveService.SelectAllRoom();
    PageHelper.startPage(pageNum, pageSize);
    List<ResersvationRoomCar> roomCars = new ArrayList<>();
    for (ResersvationRoomCar c:cars
         ) {
      roomCars.add(c);
    }for (ResersvationRoomCar r:rooms
         ) {
      roomCars.add(r);
    }
    List<ResersvationRoomCar> result = new ArrayList<>();
    for (ResersvationRoomCar resersvationRoomCar : roomCars) {
      if (resersvationRoomCar.getReserveState().equals(status)) {
        result.add(resersvationRoomCar);
      }
    }
    PageInfo<ResersvationRoomCar> of = PageInfo.of(result);
    Map map = new HashMap();
    map.put("status", 200);
    map.put("msg", "获取预约列表成功");
    map.put("data", of.getList());
    map.put("total", of.getTotal());
    return map;
  }

  /**
   * 创建新的预约
   *
   * @param userId 用户id
   * @param req    请求体
   * @param type   预约资源类型
   * @return
   * @throws ParseException
   */
  @PostMapping("/reserve/{type}/{userId}")
  public ResponseDto createReserve(@PathVariable String userId, @RequestBody Map<String, String> req, @PathVariable String type) throws ParseException {

    Reservation reservation = new Reservation();

    //获取用户id
    Integer userId_ = Integer.parseInt(userId);
    if (TYPE_CAR.equals(type)) {
      Integer carId_ = Integer.parseInt(req.get("carId"));
      reservation.setCarId(carId_);
    }
    if (TYPE_ROOM.equals(type)) {
      Integer roomId_ = Integer.parseInt(req.get("roomId"));
      reservation.setRoomId(roomId_);
    }

    //获取申请理由
    String applyReason = req.get("applyReason");

    //获取预约时间
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = simpleDateFormat.parse(req.get("startTime"));
    Date endTime = simpleDateFormat.parse(req.get("endTime"));

    reservation.setUserId(userId_);
    reservation.setApplyReason(applyReason);
    reservation.setCreateTime(new Date());
    reservation.setStartTime(startTime);
    reservation.setEndTime(endTime);

    reserveService.createReserve(reservation);
    return new ResponseDto(200, "申请预约成功", reservation);
  }

  /**
   * 通过id进行定位删除
   * @param id
   * @return
   */
  @GetMapping("/delKeyId/{id}")
  public ResponseDto delByReservationId(@PathVariable("id") String id){
    Integer i = Integer.parseInt(id);
    int i1 = reserveService.delById(i);
    return new ResponseDto(200,"删除成功",i1);

  }


  /**
   * 根据用户ID 和预约状态 查预约信息
   *
   * @param userId 用户ID
   * @param state  预约状态
   * @return
   */
  @GetMapping("/reserve/{userId}")
  public ResponseDto selByUserId(@PathVariable("userId") String userId, @RequestParam("state") String state) {

    List<Object> objects = new ArrayList<>();
    Integer userId_ = Integer.parseInt(userId);
    List<ResersvationRoomCar> rooms = reserveService.selRoomByUserId(userId_, state);
    List<ResersvationRoomCar> cars = reserveService.selCarByUserId(userId_, state);
    //由于传回来的数据是数组类型的，所以将他们的元素都单独取出来，存储在list里面
    for (ResersvationRoomCar r : rooms) {
      objects.add(r);
    }
    for (ResersvationRoomCar c : cars) {
      objects.add(c);
    }
    return new ResponseDto(200, "获取预约信息成功", objects);
  }

  /**
   * 对预约信息进行更新，必须设定开始和结束时间
   * @param reserveId
   * @param req
   * @return
   * @throws ParseException
   */
  @PutMapping("/reserve/{reserveId}")
  public ResponseDto updateReserve(@PathVariable String reserveId, @RequestBody Map<String, String> req) throws ParseException {

    Integer reserveId_ = Integer.parseInt(reserveId);

    //获取预约时间
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = simpleDateFormat.parse(req.get("startTime"));
    Date endTime = simpleDateFormat.parse(req.get("endTime"));

    String applyReason = req.get("applyReason");

    Reservation reservation = new Reservation();
    reservation.setReserveId(reserveId_);
    reservation.setReserveState("申请中");
    reservation.setStartTime(startTime);
    reservation.setEndTime(endTime);
    reservation.setApplyReason(applyReason);
    reservation.setRejectReason("");
    reserveService.updateReserve(reservation);

    return new ResponseDto(200, "操作成功");
  }

  /**
   * 更新用户提交的申请状态，拒绝则返回拒绝理由
   * @param reserveId
   * @param status
   * @param
   * @return
   */
  @PutMapping("/reserve/{status}/{reserveId}")
  public ResponseDto update(@PathVariable String reserveId, @PathVariable String status,@RequestBody(required = false) Map<String, String>  req) {
    int i = Integer.parseInt(reserveId);
    Reservation reservation = new Reservation();
    reservation.setReserveId(i);
    if ("pass".equals(status)) {
      reservation.setReserveState("已通过");
    } else if ("reject".equals(status)) {
      reservation.setReserveState("已驳回");
      reservation.setRejectReason(req.get("rejectReason"));
    }
    reserveService.updateReserve(reservation);
    return new ResponseDto(200, "操作成功");
  }

  /**
   * 通过carId进行查找用户信息
   * @param carId
   * @return
   */
  @GetMapping("/reserve/car/{carId}")
  public ResponseDto selectUserByCarId(@PathVariable("carId") String carId){
    int i = Integer.parseInt(carId);
    List<ResersvationRoomCar> carid = reserveService.selectUserByCarid(i);
    return new ResponseDto(200,"查询（car）成功",carid);
  }

  /**
   * 通过roomId进行查找用户信息
   * @param roomId
   * @return
   */
  @GetMapping("/reserve/room/{roomId}")
  public ResponseDto selectUserByRoomId(@PathVariable("roomId") String roomId){
    int i = Integer.parseInt(roomId);
    List<ResersvationRoomCar> roomid = reserveService.selectUserByRoomid(i);
    return new ResponseDto(200,"查询（room）成功",roomid);
  }
}
